import fs from 'fs';
import Path from 'path';
import { tools } from './tools/tools';
import { format_genrator } from './format_genrator'

export namespace resToolClass {

    /**
     * @param rootPath  项目路径
     * @returns config.json文件内容
     */
    export async function getResTreeData(rootPath: string): Promise<string[]> {
        let fileStr = fs.readFileSync(Path.join(rootPath, "resource_cfg/config.json"), { encoding: "utf-8" });
        let fileDataArr: any[] = JSON.parse(fileStr);
        for (let i = 0, length = fileDataArr.length; i < length; i++) {
            let fileItem: any = fileDataArr[i]
            if (!fileItem) {
                continue;
            }
            let path: string = Path.join(rootPath, "resource/");
            let includeArr: string[] = await tools.GlobFiles(fileItem.include, fileItem.exclude, path) || [];
            fileItem.include = [];
            fileItem.exclude = [];
            for (let i = 0, length = includeArr.length; i < length; i++) {
                let str = includeArr[i];
                fileItem.include.push(str.substr(path.length));
            }
        }
        return new Promise<string[]>((rejects) => {
            rejects(fileDataArr);
        });
    }

    /**
     * 
     * @param rootPath 项目路径
     * @param dirPath 文件夹名
     * @param fileName 文件名
     * @returns 
     */
    export async function getGroupTreeData(rootPath: string, dirPath: string, fileName: string): Promise<string[]> {
        let fileStr = fs.readFileSync(Path.join(rootPath, "resource_cfg", dirPath, fileName), { encoding: "utf-8" });
        if (!fileStr) {
            return [];
        }
        let fileObj: any = JSON.parse(fileStr);
        let path: string = Path.join(rootPath, "resource/");
        let includeArr: string[] = await tools.GlobFiles(fileObj.include, fileObj.exclude, path) || [];
        for (let i = 0, length = includeArr.length; i < length; i++) {
            includeArr[i] = includeArr[i].substr(path.length);
        }
        return new Promise<any[]>((rejects) => {
            rejects(includeArr);
        });
    }

    /**
     * 
     * @param rootPath 项目路径
     * @param strPath 拖拽文件路径数组
     * @returns 
     */
    export async function checkDropFiles(rootPath: string, strPath: string[]): Promise<string[]> {
        let curPath: string = Path.join(rootPath, "resource/");
        let strArr: string[] = []
        for (let i = 0, length = strPath.length; i < length; i++) {
            let path = strPath[i];
            if (path.indexOf(curPath) < 0) {
                //不在项目路径下
                continue;
            }
            strArr.push(strPath[i].substr(curPath.length));
        }
        let fileArr: string[] = [];
        //如果是文件夹 需遍历所有子文件 包括 子文件夹文件
        for (let i = 0, length = strArr.length; i < length; i++) {
            let path = Path.join(curPath, strArr[i]);
            let state: fs.Stats = fs.statSync(path)
            if (state.isFile()) {
                let str = strArr[i].split("\\").join("/");
                fileArr.push(str);
            }
            if (state.isDirectory()) {
                let dirAllFile: string[] = await tools.GlobFiles([path + "/**/*.*"], []) || [];
                for (let j = 0, length = dirAllFile.length; j < length; j++) {
                    dirAllFile[j] = dirAllFile[j].substr(curPath.length)
                }
                fileArr = fileArr.concat(dirAllFile);
            }
        }
        return new Promise<string[]>((rejects) => {
            rejects(fileArr);
        });
    }

    /**
     * 
     * @param rootPath  "E:/workspace/SSSS"
     * @param keyName   "default.res.json"
     * @param includeArr 
     * @returns 
     */
    export async function writeCfgFile(rootPath: string, keyName: string, includeArr: string[]): Promise<boolean> {

        let fileStr = fs.readFileSync(Path.join(rootPath, "resource_cfg/config.json"), { encoding: "utf-8" });
        if (!fileStr) {
            return false;
        }
        let resArr: tools.GENRATOR_CFG_TYPE[] = JSON.parse(fileStr);
        if (!resArr || resArr.length <= 0) {
            return false;
        }
        
        for (let i = 0,length = resArr.length; i < length; i++) {
            let res: tools.GENRATOR_CFG_TYPE = resArr[i];
            if(!res || res.name != keyName){
                continue
            }
            let formatedData = await new format_genrator.CfgFormat().resFormat(rootPath + '/resource/', includeArr);
            res.include = formatedData.include;
            res.exclude = formatedData.exclude;
            break;
        }

        fs.writeFileSync(Path.join(rootPath, "resource_cfg/config.json"), JSON.stringify(resArr, null, 4), {
            encoding: 'utf-8'
        });
        return true;
    }

    /**
     * 
     * @param rootPath "E:/workspace/SSSS"
     * @param includeArr 
     * @param filePath group_cfg_default_res_json/cfgjson.json
     */
    export async function writeGroupFile(rootPath: string, filePath: string, includeArr: string[]): Promise<boolean> {

        let formatedData = await new format_genrator.CfgFormat().resFormat(rootPath + '/resource/', includeArr);

        let tmpData: tools.GROUP_CFG_TYPE = {
            include: formatedData.include,
            exclude: formatedData.exclude
        }

        fs.writeFileSync(Path.join(rootPath,"resource_cfg",filePath), JSON.stringify(tmpData, null, 4), {
            encoding: 'utf-8'
        });
        return true;
    }
}